package com.hj.ct.view;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.hj.ct.R;
import com.hj.ct.wheelview.NumericWheelAdapter;
import com.hj.ct.wheelview.OnWheelScrollListener;
import com.hj.ct.wheelview.WheelView;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class WheelDialog extends Dialog {
	
	private LayoutInflater inflater;
	private View convertView;
	private TextView mLeftTitleText, yeartext, monthtext, daytext, hourtext;
	private LinearLayout yearLayout, monthLayout, dayLayout, hourLayout;
	private WheelView wv_year, wv_month, wv_day, wv_hour;
	
	private int startNum = -1, secondNum = -1, thirdNum = -1, fourthNum=-1;
	
	private OnMyOnPickListener mOnPickListener;
	private String key = "deliver_at";
	private String lable = "起始时间";
    private String firstdata = "年,1902,2014,false,114";
    private String seconddata = "月,1,12,true,2";
    private String thirddata = "日,1,31,false,2";
    private String fourthdata = "时,0,23,false,2";
    
	public WheelDialog(Context context) {
		this(context, R.style.NoTitleBgDialog);
		setData(key, lable, firstdata, seconddata, thirddata,fourthdata);
	}
	
	public void setOnPickListener(OnMyOnPickListener listener) {
		this.mOnPickListener = listener;
	}
	
	public void setData(String key, String lable, String firstdata, String seconddata, String thirddata, String fourthdata) {
		this.firstdata = firstdata;
		this.seconddata = seconddata;
		this.thirddata = thirddata;
		this.fourthdata = fourthdata;
		this.lable = lable;
		this.key = key;
		prepareShowData();
	}
	
	public WheelDialog(Context context, int theme) {
		super(context, theme);
		inflater = LayoutInflater.from(context);
		convertView = inflater.inflate(R.layout.dialog_date_layout, null);
		setContentView(convertView);
		initView();
		
	}
	
	private void initView() {
		mLeftTitleText = (TextView) convertView.findViewById(R.id.yearTitleTextView);
		yearLayout = (LinearLayout) convertView.findViewById(R.id.yearLayout);
		yeartext = (TextView) yearLayout.findViewById(R.id.yeartext);
		wv_year = (WheelView) yearLayout.findViewById(R.id.year);
		monthLayout = (LinearLayout) convertView.findViewById(R.id.monthLayout);
		monthtext = (TextView) monthLayout.findViewById(R.id.monthtext);
		wv_month = (WheelView) monthLayout.findViewById(R.id.month);
		dayLayout = (LinearLayout) convertView.findViewById(R.id.dayLayout);
		daytext = (TextView) dayLayout.findViewById(R.id.daytext);
		wv_day = (WheelView) dayLayout.findViewById(R.id.day);
		hourLayout = (LinearLayout) convertView.findViewById(R.id.hourLayout);
		hourtext = (TextView) hourLayout.findViewById(R.id.hourtext);
		wv_hour = (WheelView) hourLayout.findViewById(R.id.hour);
		wv_year.setVisibleItems(3);
		wv_month.setVisibleItems(3);
		wv_day.setVisibleItems(3);
		wv_hour.setVisibleItems(3);
		Button btn_sure = (Button) convertView.findViewById(R.id.btn_datetime_sure);
		Button btn_cancel = (Button) convertView.findViewById(R.id.btn_datetime_cancel);
		
		btn_sure.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String tag = String.valueOf(wv_year.getCurrentItem() + startNum);
				int month = wv_month.getCurrentItem() + secondNum;
				int day = wv_day.getCurrentItem() + thirdNum;
				int hour = wv_hour.getCurrentItem() + fourthNum;
				String tag_month = month > 9 ? month + "" : "0" + month;
				String tag_day = day > 9 ? day + "" : "0" + day;
				String tag_hour = hour > 9 ? hour + "" : "0" + hour;
				if (key != null && key.equals("deliver_at")){
					tag = secondNum != -1 ? tag + "-" + tag_month : tag;
					tag = thirdNum != -1 ? tag + "-" + tag_day : tag;
					tag = fourthNum != -1 ? tag + " " + tag_hour : tag;
				}else{
					tag = secondNum != -1 ? tag + "-" + month : tag;
					tag = thirdNum != -1 ? tag + "-" + day : tag;
					tag = fourthNum != -1 ? tag + " " + hour : tag;
				}

				mOnPickListener.onPickData(key, tag);
				dismiss();
				
			}
		});
		
		btn_cancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				dismiss();
			}
		});
		
	}
	
	private void prepareShowData() {
		yearLayout.setVisibility(View.GONE);
		monthLayout.setVisibility(View.GONE); 
		dayLayout.setVisibility(View.GONE);
		hourLayout.setVisibility(View.GONE);
		mLeftTitleText.setText(lable.trim().replaceAll(" ", ""));
		Calendar calender = Calendar.getInstance();
		if (firstdata != null) {
			String[] firsts = firstdata.split(",");
			if (firsts != null && firsts.length != 5) {
				return;
			}
			yearLayout.setVisibility(View.VISIBLE);
			yeartext.setText(firsts[0]);
			startNum = Integer.parseInt(firsts[1]);
			NumericWheelAdapter numericApdapter = null;
			if (TextUtils.equals(key, "ping_che_hour_mins")) {
				numericApdapter = new NumericWheelAdapter(startNum, Integer.parseInt(firsts[2]), "%02d");
				wv_year.setAdapter(numericApdapter);// 设置"年"的显示数据
			}else if(TextUtils.equals(key, "deliver_at")){
				numericApdapter = new NumericWheelAdapter(startNum, calender.get(Calendar.YEAR));
				wv_year.setAdapter(numericApdapter);
			} else {
				numericApdapter = new NumericWheelAdapter(startNum, Integer.parseInt(firsts[2]));
				wv_year.setAdapter(numericApdapter);// 设置"年"的显示数据
			}
			wv_year.setCyclic(Boolean.parseBoolean(firsts[3]));
			wv_year.addScrollingListener(new OnMyWheelScrollListener());
			wv_year.setCurrentItem(Integer.parseInt(firsts[4]));// 初始化时显示的数据
			
		}
		if (seconddata != null) {
			String[] seconds = seconddata.split(",");
			if (seconds != null && seconds.length != 5) {
				return;
			}
			monthLayout.setVisibility(View.VISIBLE);
			monthtext.setText(seconds[0]);
			secondNum = Integer.parseInt(seconds[1]);
			if (TextUtils.equals(key, "ping_che_hour_mins")) {
				wv_month.setAdapter(new NumericWheelAdapter(Integer.parseInt(seconds[1]), Integer.parseInt(seconds[2]), "%02d",
						NumericWheelAdapter.EXTRA_FROM_ADD_10));// 设置"年"的显示数据
			} else {
				wv_month.setAdapter(new NumericWheelAdapter(Integer.parseInt(seconds[1]), Integer.parseInt(seconds[2])));// 设置"年"的显示数据
			}
			wv_month.setCyclic(Boolean.parseBoolean(seconds[3]));
			wv_month.addScrollingListener(new OnMyWheelScrollListener());
			wv_month.setCurrentItem(Integer.parseInt(seconds[4]));
		}
		if (thirddata != null) {
			String[] thirds = thirddata.split(",");
			if (thirds != null && thirds.length != 5) {
				return;
			}
			dayLayout.setVisibility(View.VISIBLE);
			daytext.setText(thirds[0]);
			thirdNum = Integer.parseInt(thirds[1]);
			wv_day.setAdapter(new NumericWheelAdapter(Integer.parseInt(thirds[1]), Integer.parseInt(thirds[2])));// 设置"年"的显示数据
			wv_day.setCyclic(Boolean.parseBoolean(thirds[3]));
			wv_day.addScrollingListener(new OnMyWheelScrollListener());
			wv_day.setCurrentItem(Integer.parseInt(thirds[4]));
		}
		if (fourthdata != null) {
			String[] fourthes = fourthdata.split(",");
			if (fourthes != null && fourthes.length != 5) {
				return;
			}
			hourLayout.setVisibility(View.VISIBLE);
			hourtext.setText(fourthes[0]);
			fourthNum = Integer.parseInt(fourthes[1]);
			wv_hour.setAdapter(new NumericWheelAdapter(Integer.parseInt(fourthes[1]), Integer.parseInt(fourthes[2])));// 设置"年"的显示数据
			wv_hour.setCyclic(Boolean.parseBoolean(fourthes[3]));
			wv_hour.addScrollingListener(new OnMyWheelScrollListener());
			wv_hour.setCurrentItem(Integer.parseInt(fourthes[4]));
		}
		
	}
	
	private void updateDayView(){
		if (thirddata != null) {
			String[] thirds = thirddata.split(",");
			if (thirds != null && thirds.length != 5) {
				return;
			}
			dayLayout.setVisibility(View.VISIBLE);
			daytext.setText(thirds[0]);
			thirdNum = Integer.parseInt(thirds[1]);
			int maxday = Integer.parseInt(thirds[2]);
			try {
				maxday = getDays((wv_year.getCurrentItem() + startNum) + "-" + (wv_month.getCurrentItem() + secondNum) + "-" + "1");
			} catch (Exception e) {
				e.printStackTrace();
			}
			wv_day.setAdapter(new NumericWheelAdapter(Integer.parseInt(thirds[1]), maxday));// 设置"年"的显示数据
			wv_day.setCyclic(Boolean.parseBoolean(thirds[3]));
			wv_day.addScrollingListener(new OnMyWheelScrollListener());
			wv_day.setCurrentItem(Integer.parseInt(thirds[4]));
		}
	}
	
	/*计算某月中的天数。
	参数 strDate 的格式为：yyyy-MM-dd HH， 其中年、月、日不能为零，日用1来补位
	*/
	private int getDays(String strDate) throws Exception {
        int days = 0;
        try {
            if (!"".equals(strDate)) {
                // 设置日期显示格式，
                SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd HH");
                Date date = sdf.parse(strDate);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            }
        } catch (Exception e) {
            throw e;
        }
        return days;
    }
	
	private class OnMyWheelScrollListener implements OnWheelScrollListener {
		
		@Override
		public void onScrollingStarted(WheelView wheel) {
			
		}
		
		@Override
		public void onScrollingFinished(WheelView wheel) {
			if (wheel.getId() == R.id.month && TextUtils.equals(key, "deliver_at")
					|| (wheel.getId() == R.id.year && TextUtils.equals(key, "deliver_at") && ((wv_month.getCurrentItem() + secondNum) == 2))){
				updateDayView();
			}
		}
		
		@Override
		public void onScrolling(WheelView wheel) {
			
		}
		
	}
	
	public interface OnMyOnPickListener {
		void onPickData(String key, String tag);
	}
	
	@Override
	public void show() {
		this.getWindow().getAttributes().width = LayoutParams.MATCH_PARENT;
		super.show();
	}

}
